/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * UILogger.java
 *
 * Created on 2011-8-1, 14:56:01
 */
package net.labthink.instrument.device;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import net.labthink.instrument.device.OxygenTransducer.codec.OxygenTransducerOxyProtocolCodecFactory;
import net.labthink.instrument.device.OxygenTransducer.codec.OxygenTransducerProtocolCodecFactory;
import net.labthink.instrument.device.OxygenTransducer.handler.OxygenTransducerHandler;
import net.labthink.instrument.device.OxygenTransducer.handler.OxygenTransducerOxyHandler;
import net.labthink.instrument.device.OxygenTransducer.message.DataHolder;
import net.labthink.instrument.device.OxygenTransducer.message.OxygenTransducerOutMessage;
import net.labthink.instrument.device.OxygenTransducer.message.OxygenTransducerOxyOutMessage;
import net.labthink.instrument.rs232.RS232Connector;
import net.labthink.instrument.rs232.RS232Connector2;
import net.labthink.utils.ExtensionFileFilter;
import net.labthink.utils.GUIPrintStream;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.serial.SerialAddress;
import org.apache.mina.transport.serial.SerialAddress.DataBits;
import org.apache.mina.transport.serial.SerialAddress.FlowControl;
import org.apache.mina.transport.serial.SerialAddress.Parity;
import org.apache.mina.transport.serial.SerialAddress.StopBits;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.labels.XYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.TimeSeriesDataItem;

/**
 *
 * @author Mosliu
 */
public class UILogger extends javax.swing.JFrame {

    int testtype = 1;
    SerialAddress portAddress;
    IoHandlerAdapter handler = null;
    RS232Connector receiver = null;
    SerialAddress portAddress2;
    IoHandlerAdapter handler2 = null;
    RS232Connector2 receiver2 = null;
    GUIPrintStream gpstream;
    Thread t;
    DataHolder dh = new DataHolder();

    /** Creates new form UILogger */
    public UILogger() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel_functions = new javax.swing.JPanel();
        jPanel_comportset1 = new javax.swing.JPanel();
        jLabel_ComPort1 = new javax.swing.JLabel();
        jComboBox_ComPort = new javax.swing.JComboBox();
        jLabel_BaudRate1 = new javax.swing.JLabel();
        jComboBox_BaudRate = new javax.swing.JComboBox();
        jComboBox_BaudRate2 = new javax.swing.JComboBox();
        jLabel_BaudRate2 = new javax.swing.JLabel();
        jComboBox_ComPort2 = new javax.swing.JComboBox();
        jLabel_ComPort2 = new javax.swing.JLabel();
        jPanel_operates = new javax.swing.JPanel();
        jButton_emptyoutput = new javax.swing.JButton();
        jButton_saveoutput = new javax.swing.JButton();
        jCheckBox_autoclear = new javax.swing.JCheckBox();
        jFormattedTextField_autoclear = new javax.swing.JFormattedTextField();
        jCheckBox_autosave = new javax.swing.JCheckBox();
        jPanel_output = new javax.swing.JPanel();
        jScrollPane_output = new javax.swing.JScrollPane();
        jTextArea_output = new javax.swing.JTextArea();
        jTabbedPane_All = new javax.swing.JTabbedPane();
        jPanel_temprature = new javax.swing.JPanel();
        jToggleButton_temprature = new javax.swing.JToggleButton();
        jPanel_tempchart = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jLabel_temptext = new javax.swing.JLabel();
        jLabel_tempvalue = new javax.swing.JLabel();
        jLabel_ppmvalue = new javax.swing.JLabel();
        jLabel_ppmtext = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("温度监控曲线");

        jPanel_functions.setBorder(javax.swing.BorderFactory.createTitledBorder("功能设置"));

        jPanel_comportset1.setBorder(javax.swing.BorderFactory.createTitledBorder("串口设置"));

        jLabel_ComPort1.setText("端口1设置");

        jComboBox_ComPort.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8" }));

        jLabel_BaudRate1.setText("速率");

        jComboBox_BaudRate.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "110", "300", "600", "1200", "2400", "4800", "9600", "14400", "19200", "38400", "43000", "56000", "57600", "115200" }));
        jComboBox_BaudRate.setSelectedIndex(6);

        jComboBox_BaudRate2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "110", "300", "600", "1200", "2400", "4800", "9600", "14400", "19200", "38400", "43000", "56000", "57600", "115200" }));
        jComboBox_BaudRate2.setSelectedIndex(6);

        jLabel_BaudRate2.setText("速率");

        jComboBox_ComPort2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "None", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8" }));
        jComboBox_ComPort2.setSelectedIndex(2);

        jLabel_ComPort2.setText("端口2设置");

        javax.swing.GroupLayout jPanel_comportset1Layout = new javax.swing.GroupLayout(jPanel_comportset1);
        jPanel_comportset1.setLayout(jPanel_comportset1Layout);
        jPanel_comportset1Layout.setHorizontalGroup(
            jPanel_comportset1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_comportset1Layout.createSequentialGroup()
                .addComponent(jLabel_ComPort1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox_ComPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel_BaudRate1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox_BaudRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel_ComPort2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox_ComPort2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel_BaudRate2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox_BaudRate2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(113, Short.MAX_VALUE))
        );
        jPanel_comportset1Layout.setVerticalGroup(
            jPanel_comportset1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_comportset1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel_ComPort1)
                .addComponent(jComboBox_ComPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel_BaudRate1)
                .addComponent(jComboBox_BaudRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel_ComPort2)
                .addComponent(jComboBox_ComPort2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jLabel_BaudRate2)
                .addComponent(jComboBox_BaudRate2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jPanel_operates.setBorder(javax.swing.BorderFactory.createTitledBorder("操作"));

        jButton_emptyoutput.setText("清空");
        jButton_emptyoutput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_emptyoutputActionPerformed(evt);
            }
        });

        jButton_saveoutput.setText("保存");
        jButton_saveoutput.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton_saveoutputActionPerformed(evt);
            }
        });

        jCheckBox_autoclear.setText("AutoClear");
        jCheckBox_autoclear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox_autoclearActionPerformed(evt);
            }
        });

        jFormattedTextField_autoclear.setEnabled(false);
        jFormattedTextField_autoclear.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jFormattedTextField_autoclearFocusLost(evt);
            }
        });

        jCheckBox_autosave.setText("AutoSave");
        jCheckBox_autosave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox_autosaveActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel_operatesLayout = new javax.swing.GroupLayout(jPanel_operates);
        jPanel_operates.setLayout(jPanel_operatesLayout);
        jPanel_operatesLayout.setHorizontalGroup(
            jPanel_operatesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_operatesLayout.createSequentialGroup()
                .addComponent(jButton_emptyoutput, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton_saveoutput, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jCheckBox_autosave)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCheckBox_autoclear)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jFormattedTextField_autoclear, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel_operatesLayout.setVerticalGroup(
            jPanel_operatesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_operatesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton_emptyoutput)
                .addComponent(jCheckBox_autoclear)
                .addComponent(jFormattedTextField_autoclear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton_saveoutput)
                .addComponent(jCheckBox_autosave))
        );

        javax.swing.GroupLayout jPanel_functionsLayout = new javax.swing.GroupLayout(jPanel_functions);
        jPanel_functions.setLayout(jPanel_functionsLayout);
        jPanel_functionsLayout.setHorizontalGroup(
            jPanel_functionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_functionsLayout.createSequentialGroup()
                .addComponent(jPanel_comportset1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel_operates, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel_functionsLayout.setVerticalGroup(
            jPanel_functionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_functionsLayout.createSequentialGroup()
                .addGroup(jPanel_functionsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel_operates, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel_comportset1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel_output.setBorder(javax.swing.BorderFactory.createTitledBorder("信息输出区"));

        jTextArea_output.setColumns(20);
        jTextArea_output.setRows(5);
        jScrollPane_output.setViewportView(jTextArea_output);

        javax.swing.GroupLayout jPanel_outputLayout = new javax.swing.GroupLayout(jPanel_output);
        jPanel_output.setLayout(jPanel_outputLayout);
        jPanel_outputLayout.setHorizontalGroup(
            jPanel_outputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane_output, javax.swing.GroupLayout.DEFAULT_SIZE, 959, Short.MAX_VALUE)
        );
        jPanel_outputLayout.setVerticalGroup(
            jPanel_outputLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane_output, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)
        );

        jToggleButton_temprature.setText("开始");
        jToggleButton_temprature.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton_tempratureActionPerformed(evt);
            }
        });

        jPanel_tempchart.setBorder(javax.swing.BorderFactory.createTitledBorder(""));

        javax.swing.GroupLayout jPanel_tempchartLayout = new javax.swing.GroupLayout(jPanel_tempchart);
        jPanel_tempchart.setLayout(jPanel_tempchartLayout);
        jPanel_tempchartLayout.setHorizontalGroup(
            jPanel_tempchartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 934, Short.MAX_VALUE)
        );
        jPanel_tempchartLayout.setVerticalGroup(
            jPanel_tempchartLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 346, Short.MAX_VALUE)
        );

        jButton1.setText("导出");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel_temptext.setText("当前温度（℃）：");

        jLabel_tempvalue.setText("0");

        jLabel_ppmvalue.setText("0");

        jLabel_ppmtext.setText("当前ppm：");

        javax.swing.GroupLayout jPanel_tempratureLayout = new javax.swing.GroupLayout(jPanel_temprature);
        jPanel_temprature.setLayout(jPanel_tempratureLayout);
        jPanel_tempratureLayout.setHorizontalGroup(
            jPanel_tempratureLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel_tempratureLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel_tempratureLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel_tempchart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel_tempratureLayout.createSequentialGroup()
                        .addComponent(jToggleButton_temprature)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel_temptext)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel_tempvalue, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel_ppmtext)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel_ppmvalue, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel_tempratureLayout.setVerticalGroup(
            jPanel_tempratureLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel_tempratureLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel_tempchart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel_tempratureLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jToggleButton_temprature)
                    .addComponent(jButton1)
                    .addComponent(jLabel_temptext)
                    .addComponent(jLabel_tempvalue)
                    .addComponent(jLabel_ppmtext)
                    .addComponent(jLabel_ppmvalue))
                .addContainerGap())
        );

        jTabbedPane_All.addTab("温度监视", jPanel_temprature);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jTabbedPane_All, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 975, Short.MAX_VALUE)
                    .addComponent(jPanel_output, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel_functions, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane_All, javax.swing.GroupLayout.DEFAULT_SIZE, 444, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel_functions, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel_output, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton_emptyoutputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_emptyoutputActionPerformed
        gpstream.clear();
        //        System.out.flush();
        //        System.out.close();
        jTextArea_output.setText("");
        //        System.setOut(new GUIPrintStream(System.out, ut.jTextArea_output));
    }//GEN-LAST:event_jButton_emptyoutputActionPerformed

    private void jButton_saveoutputActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton_saveoutputActionPerformed
        //        JOptionPane.showConfirmDialog(jLabel_ComPort, "本功能暂未实现，留待下一版本想起来再说");
        ExtensionFileFilter filter = new ExtensionFileFilter("log,txt", true);
        filter.setDescription("日志文件 ");
        JFileChooser jfc = new JFileChooser();
        jfc.setDialogTitle("选择保存位置");
        jfc.setMultiSelectionEnabled(false);
        jfc.setDialogType(JFileChooser.SAVE_DIALOG);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setFileFilter(filter);
        int result = jfc.showOpenDialog(this);  // 打开"打开文件"对话框
        if (result == JFileChooser.APPROVE_OPTION) {
            String file = jfc.getSelectedFile().getAbsolutePath();
            int dotindex = file.indexOf(".");
            if (dotindex < 0) {
                file = file + ".log";
            }
            try {
                FileWriter fw = new FileWriter(file, true);
                //                FileWriter fw = new FileWriter(jfc.getSelectedFile(), true);
                fw.append(jTextArea_output.getText());
                fw.close();
            } catch (IOException ex) {
                Logger.getLogger(UITester.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
}//GEN-LAST:event_jButton_saveoutputActionPerformed

    private void jCheckBox_autoclearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_autoclearActionPerformed
        if (jCheckBox_autoclear.isSelected()) {
            jFormattedTextField_autoclear.setEnabled(true);
            jFormattedTextField_autoclear.setValue(20000);
            gpstream.setAutoclear(true);
            gpstream.setAutoclearcount((Integer) jFormattedTextField_autoclear.getValue());
        } else {
            jFormattedTextField_autoclear.setEnabled(false);
            jFormattedTextField_autoclear.setText("");
            gpstream.setAutoclear(false);
            //            jFormattedTextField_autoclear.setValue(0);
        }
}//GEN-LAST:event_jCheckBox_autoclearActionPerformed

    private void jFormattedTextField_autoclearFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jFormattedTextField_autoclearFocusLost
        gpstream.setAutoclearcount((Integer) jFormattedTextField_autoclear.getValue());
        System.out.println("设置自动清空上限为：" + (Integer) jFormattedTextField_autoclear.getValue());
}//GEN-LAST:event_jFormattedTextField_autoclearFocusLost

    private void jCheckBox_autosaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_autosaveActionPerformed
        // TODO add your handling code here:
        // TODO add your handling code here:
        if (jCheckBox_autosave.isSelected()) {
            //            jFormattedTextField_autoclear.setEnabled(true);
            //            jFormattedTextField_autoclear.setValue(20000);
            gpstream.setLogFileFlag(true);
            //            gpstream.setAutoclear(true);
            //            gpstream.setAutoclearcount((Integer) jFormattedTextField_autoclear.getValue());
        } else {
            gpstream.setLogFileFlag(false);
            //            jFormattedTextField_autoclear.setEnabled(false);
            //            jFormattedTextField_autoclear.setText("");
            //            gpstream.setAutoclear(false);
            //            jFormattedTextField_autoclear.setValue(0);
        }
}//GEN-LAST:event_jCheckBox_autosaveActionPerformed

    private void jToggleButton_tempratureActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton_tempratureActionPerformed
        // TODO add your handling code here:
//第一个串口设置
        portAddress = getserialport();

        handler = new OxygenTransducerHandler(dh);
//        ((OxygenTransducerHandler) handler).loadData();

        if (receiver != null) {
            receiver.endListen();
        }
        receiver = RS232Connector.getInstance(handler, portAddress);

        receiver.addFilter("logger", new LoggingFilter());
        receiver.addFilter("codec", new ProtocolCodecFilter(new OxygenTransducerProtocolCodecFactory()));    // 设置编码过滤器

//第二个串口设置

        portAddress2 = getserialport2();
        boolean start2 = portAddress2 != null;
        if (start2) {
            handler2 = new OxygenTransducerOxyHandler(dh);
//        ((OxygenTransducerOxyHandler) handler2).loadData();

            if (receiver2 != null) {
                receiver2.endListen();
            }
            receiver2 = RS232Connector2.getInstance(handler2, portAddress2);

            receiver2.addFilter("logger2", new LoggingFilter());
            receiver2.addFilter("codec2", new ProtocolCodecFilter(new OxygenTransducerOxyProtocolCodecFactory()));    // 设置编码过滤器
        }
        byte b = (byte) 'R';
        //取温度表数据
        final OxygenTransducerOutMessage pkt = new OxygenTransducerOutMessage();
        byte[] bt1 = {(byte) 0x81, (byte) 0x81, 0x52, 0x1a, 0, 0, 0x53, 0x1a};
        pkt.setContent(bt1);
        //取氧变送器数据
        final OxygenTransducerOxyOutMessage pkt2 = new OxygenTransducerOxyOutMessage();
        byte[] bt2 = {(byte) 'R'};
        pkt2.setContent(bt2);


        Timer timer = new Timer();
        Timer timer2 = new Timer();

        // receiver.addFilter("codec", new ProtocolCodecFilter(
        // new TextLineCodecFactory(Charset.forName("UTF-8")))); // 设置编码过滤器
        if (jToggleButton_temprature.isSelected()) {
            receiver.startListen();
            final IoSession session = receiver.getReceiverSession();
            timer.scheduleAtFixedRate(new TimerTask() {

                public void run() {
                    try {
                        WriteFuture wf;
                        wf = session.write(pkt);// 发送消息
                        wf.awaitUninterruptibly();
                        Thread.sleep(300);
                        byte[] bts1 = {(byte) 0x81, (byte) 0x81, 0x52, 0x1a, 0, 0, 0x53, 0x1a};
                        pkt.setContent(bts1);
                        wf = session.write(pkt);// 发送消息
                        wf.awaitUninterruptibly();
                        Thread.sleep(300);
                        byte[] bts2 = {(byte) 0x82, (byte) 0x82, 0x52, 0x1a, 0, 0, 0x54, 0x1a};
                        pkt.setContent(bts2);
                        wf = session.write(pkt);// 发送消息
                        wf.awaitUninterruptibly();
                    } catch (InterruptedException ex) {
                        Logger.getLogger(UILogger.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }, 0, 1000);
            if (start2) {
                receiver2.startListen();
                final IoSession session2 = receiver2.getReceiverSession();
                timer2.scheduleAtFixedRate(new TimerTask() {

                    public void run() {
                        WriteFuture wf2;
                        wf2 = session2.write(pkt2);// 发送消息
                        wf2.awaitUninterruptibly();
                    }
                }, 0, 1000);
            }
            jToggleButton_temprature.setText("关闭");
        } else {
            receiver.endListen();
            timer.cancel();
            if (start2) {
                timer2.cancel();
            }
            ((OxygenTransducerHandler) handler).saveData();
            jToggleButton_temprature.setText("开始");
        }
    }//GEN-LAST:event_jToggleButton_tempratureActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        List a = dh.timeSeries.getItems();
        List b = dh.timeSeries2.getItems();


        int counta = a.size();
        int countb = b.size();
        int count = counta < countb ? counta : countb;
        if (count < 1) {
            return;
        }

        long firsta = ((TimeSeriesDataItem) a.get(0)).getPeriod().getSerialIndex();
        long firstb = ((TimeSeriesDataItem) b.get(0)).getPeriod().getSerialIndex();
        long lasta = ((TimeSeriesDataItem) a.get(counta - 1)).getPeriod().getSerialIndex();
        long lastb = ((TimeSeriesDataItem) b.get(countb - 1)).getPeriod().getSerialIndex();

        long first = firsta < firstb ? firsta : firstb;
        long last = lasta > lastb ? lasta : lastb;
        for (long curr = first; curr < last; curr++) {
//            if(dh.timeSeries.getDataItem(null))
        }
        double[][] out = new double[(int) (last - first + 1)][3];
        for (int i = 0; i < out.length; i++) {
            out[i][0] = i;
        }
        for (int i = 0; i < counta; i++) {
            TimeSeriesDataItem node = (TimeSeriesDataItem) a.get(i);
            int index = (int) (node.getPeriod().getSerialIndex() - first);
            out[index][1] = node.getValue().doubleValue();
        }
        for (int i = 0; i < countb; i++) {
            TimeSeriesDataItem node = (TimeSeriesDataItem) b.get(i);
            int index = (int) (node.getPeriod().getSerialIndex() - first);
            out[index][2] = node.getValue().doubleValue();
        }
//
//        for (int i = 0; i < count; i++) {
////            System.out.println(a.get(i).getClass());
//            TimeSeriesDataItem node = (TimeSeriesDataItem) a.get(i);
////            System.out.println(node.getPeriod().getFirstMillisecond());
////            System.out.println(node.getPeriod().getMiddleMillisecond());
////            System.out.println(node.getPeriod().getLastMillisecond());
//            System.out.println(node.getPeriod().getSerialIndex());
//
//            System.out.println(node.getValue());
//            TimeSeriesDataItem node1 = (TimeSeriesDataItem) b.get(i);
//            System.out.println(node1.getPeriod().getSerialIndex());
//            System.out.println(node1.getValue());
//            System.out.println("---------------------");
//
//
//        }
//        for (int i = 0; i < arr.length; i++) {
//            Object object = arr[i];
//
//        }
        ExtensionFileFilter filter = new ExtensionFileFilter("csv,txt", true);
        filter.setDescription("结果导出");

        JFileChooser jfc = new JFileChooser();
        jfc.setDialogTitle("选择保存位置");
        jfc.setMultiSelectionEnabled(false);
        jfc.setDialogType(JFileChooser.SAVE_DIALOG);
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setFileFilter(filter);
        int result = jfc.showOpenDialog(this);  // 打开"打开文件"对话框
        if (result == JFileChooser.APPROVE_OPTION) {
            String file = jfc.getSelectedFile().getAbsolutePath();
            int dotindex = file.indexOf(".");
            if (dotindex < 0) {
                file = file + ".csv";
            }
            try {
//                FileWriter fw = new FileWriter(jfc.getSelectedFile(), true);
                StringBuilder sb = new StringBuilder();
                sb.append("序号,温度,ppm\r\n");
                for (int i = 0; i < out.length; i++) {
                    sb.append(out[i][0]).append(",");
                    sb.append(out[i][1]).append(",");
                    sb.append(out[i][2]).append("\r\n");
                }
                FileWriter fw = new FileWriter(file, true);
                fw.append(sb);
                fw.close();
            } catch (IOException ex) {
                Logger.getLogger(UITester.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jButton1ActionPerformed

    private SerialAddress getserialport() {
        int ibaudrate = Integer.parseInt((String) jComboBox_BaudRate.getSelectedItem());
        String port = (String) jComboBox_ComPort.getSelectedItem();
        portAddress = new SerialAddress(port, ibaudrate, DataBits.DATABITS_8, StopBits.BITS_1, Parity.NONE,
                FlowControl.NONE);
        return portAddress;
    }

    private SerialAddress getserialport2() {
        int ibaudrate = Integer.parseInt((String) jComboBox_BaudRate2.getSelectedItem());
        String port = (String) jComboBox_ComPort2.getSelectedItem();
        if (port.equalsIgnoreCase("none")) {
            portAddress2 = null;
            return null;
        }
        portAddress2 = new SerialAddress(port, ibaudrate, DataBits.DATABITS_8, StopBits.BITS_1, Parity.NONE,
                FlowControl.NONE);
        return portAddress2;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(UITester.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            Logger.getLogger(UITester.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(UITester.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            Logger.getLogger(UITester.class.getName()).log(Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                UILogger ut = new UILogger();
                ut.setVisible(true);
                ut.gpstream = new GUIPrintStream(System.out, ut.jTextArea_output);
                System.setOut(ut.gpstream);
                Component cs[] = ut.jTabbedPane_All.getComponents();

                long value = 0;
                ut.dh.timeSeries = new TimeSeries("温度1", Second.class);
                ut.dh.timeSeries1 = new TimeSeries("温度2", Second.class);
                ut.dh.show1 = ut.jLabel_tempvalue;
                ut.dh.timeSeries2 = new TimeSeries("ppm", Second.class);
                ut.dh.show2 = ut.jLabel_ppmvalue;
                TimeSeriesCollection timeseriescollection = new TimeSeriesCollection(ut.dh.timeSeries);
                timeseriescollection.addSeries(ut.dh.timeSeries1);
                TimeSeriesCollection timeseriescollection1 = new TimeSeriesCollection(ut.dh.timeSeries2);
//                timeseriescollection.addSeries(ut.dh.timeSeries2);
                JFreeChart jfreechart = ChartFactory.createTimeSeriesChart("曲线", "Time(s)", "温度", timeseriescollection, true, true, false);

//                JFreeChart jfreechart = ChartFactory.createXYLineChart("Curve", "Time(s)", "Temp.", timeseriescollection,PlotOrientation.HORIZONTAL, true, true, false);
//                ChartFactory.createXYLineChart(null, null, null, dataset, PlotOrientation.HORIZONTAL, rootPaneCheckingEnabled, rootPaneCheckingEnabled, rootPaneCheckingEnabled)
                XYPlot xyplot = jfreechart.getXYPlot();
                //纵坐标设定
                ValueAxis valueaxis = xyplot.getDomainAxis();
                //水平底部列表   
                valueaxis.setLabelFont(new Font("黑体", Font.BOLD, 14));
                //水平底部标题
                valueaxis.setTickLabelFont(new Font("宋体", Font.BOLD, 12));

                //自动设置数据轴数据范围
                valueaxis.setAutoRange(true);
                //数据轴固定数据范围 7days
//                valueaxis.setFixedAutoRange(604800000D);
                valueaxis = xyplot.getRangeAxis();
                valueaxis.setLabelFont(new Font("黑体", Font.BOLD, 14));

                xyplot.setDataset(1, timeseriescollection1);
//                xyplot.getRendererCount();
//                xyplot.getRenderer(0).setSeriesPaint(0, Color.blue);
                NumberAxis numberaxis = new NumberAxis("ppm");
//                numberaxis.setAutoRangeIncludesZero(false);
                XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
                renderer.setSeriesPaint(0, Color.GREEN);
                renderer.setBaseShapesFilled(false);
                renderer.setBaseShapesVisible(false);
                XYToolTipGenerator tp = renderer.getSeriesToolTipGenerator(0);
//                renderer.setUseFillPaint(false);
//                StandardXYToolTipGenerator tg = new StandardXYToolTipGenerator();
                xyplot.setRenderer(1, renderer);
                xyplot.setRangeAxis(1, numberaxis);
                xyplot.setRangeGridlinePaint(Color.BLACK); //纵坐标格线颜色
                xyplot.setDomainGridlinePaint(Color.BLACK); //横坐标格线颜色
                xyplot.setBackgroundPaint(Color.WHITE);
                xyplot.mapDatasetToRangeAxis(1, 1);

                xyplot.getRenderer(0).setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator("温度:({1}, {2})",
                        new SimpleDateFormat("MM-dd HH:mm:ss"),
                        new DecimalFormat("0.0")));
                xyplot.getRenderer(1).setSeriesToolTipGenerator(0, new StandardXYToolTipGenerator("ppm;({1}, {2})",
                        new SimpleDateFormat("MM-dd HH:mm:ss"),
                        new DecimalFormat("0.000")));



                jfreechart.getTitle().setFont(new Font("黑体", Font.BOLD, 20));//设置标题字体
                jfreechart.getLegend().setItemFont(new Font("宋体", Font.ITALIC, 15));
                ChartPanel chartPanel = new ChartPanel(jfreechart);
                chartPanel.setSize(800, 350);
                chartPanel.setPreferredSize(new Dimension(600, 502));
                ut.jPanel_tempchart.add(chartPanel, BorderLayout.CENTER);
            }
        });


    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton_emptyoutput;
    private javax.swing.JButton jButton_saveoutput;
    private javax.swing.JCheckBox jCheckBox_autoclear;
    private javax.swing.JCheckBox jCheckBox_autosave;
    private javax.swing.JComboBox jComboBox_BaudRate;
    private javax.swing.JComboBox jComboBox_BaudRate2;
    private javax.swing.JComboBox jComboBox_ComPort;
    private javax.swing.JComboBox jComboBox_ComPort2;
    private javax.swing.JFormattedTextField jFormattedTextField_autoclear;
    private javax.swing.JLabel jLabel_BaudRate1;
    private javax.swing.JLabel jLabel_BaudRate2;
    private javax.swing.JLabel jLabel_ComPort1;
    private javax.swing.JLabel jLabel_ComPort2;
    private javax.swing.JLabel jLabel_ppmtext;
    private javax.swing.JLabel jLabel_ppmvalue;
    private javax.swing.JLabel jLabel_temptext;
    private javax.swing.JLabel jLabel_tempvalue;
    private javax.swing.JPanel jPanel_comportset1;
    private javax.swing.JPanel jPanel_functions;
    private javax.swing.JPanel jPanel_operates;
    private javax.swing.JPanel jPanel_output;
    private javax.swing.JPanel jPanel_tempchart;
    private javax.swing.JPanel jPanel_temprature;
    private javax.swing.JScrollPane jScrollPane_output;
    private javax.swing.JTabbedPane jTabbedPane_All;
    private javax.swing.JTextArea jTextArea_output;
    private javax.swing.JToggleButton jToggleButton_temprature;
    // End of variables declaration//GEN-END:variables
}
